﻿using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using User.Api.Models;

namespace User.Api
{
    public class UserContextSeed
    {
        public static async Task SeedAsync(IApplicationBuilder ApplicationBuilder, ILoggerFactory LoggerFactory, int? retry = 0)
        {
            var retryForAvaibility = retry.Value;
            using (var scope = ApplicationBuilder.ApplicationServices.CreateScope())//数据库未初始化失败会catch
            {
                try
                {
                    // var context = (AppDbContext)scope.ServiceProvider.GetRequiredService(typeof(AppDbContext));
                    var context = scope.ServiceProvider.GetRequiredService<UserDbContext>();
                    var logger = (ILogger<UserContextSeed>)scope.ServiceProvider.GetService(typeof(ILogger<UserContextSeed>));
                    logger.LogDebug("Begin UserContextSeed SeedAsyc");
                    context.Database.Migrate();
                    if (context.Users.Count()<=0)
                    {
                        context.Add(new Users { Name = "cyao", Company = "nocompany", Age=1});
                        context.SaveChanges();
                    }
                }
                catch (System.Exception ex)
                {
                    retryForAvaibility++;
                    if (retryForAvaibility > 10)
                    {
                        var logger = LoggerFactory.CreateLogger(typeof(UserContextSeed));
                        logger.LogError(ex.Message);
                        await SeedAsync(ApplicationBuilder, LoggerFactory, retryForAvaibility);
                    }
                }
            }
        }
    }
}
